package com.coder.oj.admin.controller;

import com.coder.oj.admin.dto.AdminDto;
import com.coder.oj.admin.mapstruct.AdminMapstruct;
import com.coder.oj.admin.query.AdminQuery;
import com.coder.oj.admin.service.AdminService;
import com.coder.oj.admin.vo.AdminVo;
import com.coder.oj.common.core.JsonPage;
import com.coder.oj.common.core.JwtToken;
import com.coder.oj.common.core.R;
import com.coder.oj.common.entity.Admin;
import com.coder.oj.common.mapper.AdminMapper;
import com.coder.oj.common.validate.ValidationGroups;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = {"管理员管理"})
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminMapstruct adminMapstruct;
    
    @Value("${default-password}")
    private String defaultPassword;

    @JwtToken
    @PostMapping("/page")
    @ApiOperation("分页查询")
    public R<JsonPage<AdminVo>> getAdminPage(@RequestBody AdminQuery params) {
        return R.ok().setResult(adminService.getAdminPage(params));
    }

    @JwtToken
    @GetMapping
    @ApiOperation("管理员详情")
    public R<AdminVo> getAdminById(@RequestParam("id") Long id) {
        return R.ok().setResult(adminMapstruct.toVO(adminMapper.selectById(id)));
    }

    @JwtToken
    @PostMapping
    @ApiOperation("新增管理员")
    public R saveAdmin(@Validated({ValidationGroups.Insert.class}) @RequestBody AdminDto params) {
        Admin admin = adminMapstruct.toEntity(params);
        admin.setPassword(DigestUtils.md5DigestAsHex(defaultPassword.getBytes()));
        adminMapper.insert(admin);
        return R.ok();
    }

    @JwtToken
    @PutMapping
    @ApiOperation("修改管理员")
    public R updateAdmin(@Validated({ValidationGroups.Update.class}) @RequestBody AdminDto params) {
        adminService.updateAdmin(params);
        return R.ok();
    }

    @JwtToken
    @DeleteMapping
    @ApiOperation("删除管理员")
    public R deleteAdmin(@RequestParam("id") Long id) {
        adminService.deleteAdmin(id);
        return R.ok();
    }
}
